﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Common;
using Aioms.Models;
using Furion;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Extension;
using Magicodes.ExporterAndImporter.Excel;
using Masuit.Tools.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 巡检标准
    /// </summary>
    [DynamicApiController]
    public class InspectionStandardController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public InspectionStandardController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="dvtid"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] long dvtid, [FromForm] string content, [FromForm] string type, [FromForm] string status, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            RefAsync<int> total = 0;
            List<InspectionStandard> inspectionstandards = await db.Queryable<InspectionStandard>().Where(istd => istd.Eid == eid)
                .WhereIF(!string.IsNullOrEmpty(content), istd => istd.Procedure.Contains(content))
                .WhereIF(dvtid != 0, istd => istd.Dvtid == dvtid)
                .ToPageListAsync(pageIndex, pageSize, total);
            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = inspectionstandards,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 获取工单冗余设备巡检项
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="ipid"></param>
        /// <param name="dvid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostRyList([FromForm] long eid, [FromForm] long woid, [FromForm] long ipid, [FromForm] long dvid, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            TpWorkOrder workOrders = await db.Queryable<TpWorkOrder>()
                .Where(wo => wo.Eid == eid && wo.Id == woid)
                .SingleAsync();
            XunJianPlan xunjianPlan = workOrders.TaskInfo.ToObject<XunJianPlan>();
            var data = xunjianPlan.XunJianDians.Where(xjd => xjd.Id == ipid && xjd.XunJianDevices.Any(xjdv => xjdv.Id == dvid)).Select(xjd => xjd.XunJianDevices.FirstOrDefault().DeviceXunJianStandards).ToList().FirstOrDefault().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            UnifyContext.Fill(new { Total = data?.Count });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="inspectionstandard"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] InspectionStandard inspectionstandard)
        {
            await db.Insertable<InspectionStandard>(inspectionstandard).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            InspectionStandard inspectionstandard = await db.Queryable<InspectionStandard>().Where(istd => istd.Eid == eid && istd.Id == id).SingleAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = inspectionstandard,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id)
        {
            await db.Deleteable<InspectionStandard>().Where(istd => istd.Eid == eid && istd.Id == id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="inspectionstandard"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] InspectionStandard inspectionstandard)
        {
            await db.Updateable<InspectionStandard>(inspectionstandard).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 下载模板
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PostDownloadexceltemplate()
        {
            IExcelExporter exporter = new ExcelExporter();
            var filePath = @"wwwroot/download/baoxiu/巡检标准模板.xlsx";
            var arr = new[] { "巡检步骤", "记录方式" };
            var sheetName = "巡检标准";
            var result = await exporter.ExportHeaderAsByteArray(arr, sheetName);
            result.ToExcelExportFileInfo(filePath);
            JObject data = new();
            data.Add("url", $"http://{App.HttpContext.Request.Host.Value}/download/baoxiu/巡检标准模板.xlsx");
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PostExportexcel([FromForm] long eid)
        {
            IExporter exporter = new ExcelExporter();
            var result = await exporter.Export(@"wwwroot/download/baoxiu/巡检标准.xlsx", await db.Queryable<InspectionStandard>().Where(istd => istd.Eid == eid).ToListAsync());

            JObject data = new();
            data.Add("url", $"http://{App.HttpContext.Request.Host.Value}/download/baoxiu/巡检标准.xlsx");
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostImportexcel([FromForm] long eid, [FromForm] long dvtid, [FromForm] string filePath)
        {
            //filePath = @"upload/excel/巡检标准模板.xlsx";
            string webrootpath = App.WebHostEnvironment.WebRootPath;
            FileInfo file = new(Path.Combine(webrootpath, filePath));

            long affrows = 0;
            try
            {
                using (ExcelPackage package = new(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
                    int rowCount = worksheet.Dimension.Rows;
                    var items = new List<InspectionStandard>();
                    for (int row = 2; row <= rowCount; row++)
                    {
                        items.Add(new InspectionStandard { Eid = eid, Dvtid = dvtid, Procedure = worksheet.Cells[row, 1].Value?.ToString(), Record = worksheet.Cells[row, 2].Value?.ToString(), Option = "", ImgUrl = "", VideoUrl = ""});
                    }
                    affrows = await db.Insertable(items).ExecuteCommandAsync();
                }
            }
            catch (Exception e)
            {
                affrows = -1;
                Console.WriteLine("导入巡检标准失败：" + e.Message);
            }

            if (affrows == -1)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = true,
                    Data = false,
                    Errors = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
